package org.example.binding;

import org.example.Configuration;
import org.example.session.SqlSession;

import java.util.HashMap;
import java.util.Map;

public class MapperRegistry {


    private final Configuration configuration;

    private Map<Class<?>,MapperProxyFactory<?>> map = new HashMap<>();

    public MapperRegistry(Configuration configuration) {
        this.configuration = configuration;
    }


    public void addMapper(Class<?> clazz) {
        if(clazz == null) {
            throw new RuntimeException("Mapper类实例为空");
        }
        if (!clazz.isInterface()) {
            throw new RuntimeException("Mapper必须为接口类型");
        }
        if(!hasExist(clazz)) {
            map.put(clazz,new MapperProxyFactory<>(clazz));
        }
    }


    private boolean hasExist(Class<?> clazz) {
        return map.containsKey(clazz);
    }



    public <T> T getMapper(Class<T> tClass, SqlSession sqlSession) {
        MapperProxyFactory<T> proxyFactory = (MapperProxyFactory<T>) map.get(tClass);
        if(proxyFactory == null) {
            throw new RuntimeException("Mapper未注册");
        }
        return proxyFactory.newInstance(sqlSession);
    }










}
